package com.zhiban.project.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;

public class UploadFileFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@SuppressWarnings("rawtypes")
	public List parseRequest(ServletFileUpload upload,
			HttpServletRequest request) throws FileUploadException {
		return upload.parseRequest(new ServletRequestContext(request));
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String contentType = request.getContentType();
		if (contentType != null
				&& contentType.startsWith("multipart/form-data"))
			try {
				try {
					HttpServletRequest request1 = (HttpServletRequest) request;
					request.setCharacterEncoding("utf-8");
					DiskFileItemFactory factory = new DiskFileItemFactory();
					String localDir = request.getServletContext()
							.getInitParameter("upload-dir");
					String path = localDir;
					factory.setRepository(new File(path));
					factory.setSizeThreshold(1024);
					ServletFileUpload upload = new ServletFileUpload(factory);
					@SuppressWarnings("unchecked")
					List<FileItem> list = parseRequest(upload, request1);
					for (FileItem item : list) {
						String name = item.getFieldName();
						if (StringUtils.isNotBlank(item.getName())) {
							request.setAttribute("filename", item.getName());
						}
						if (item.isFormField()) {
						} else {
							File tempFile = new File(path, "tmp");
							FileUtils.copyInputStreamToFile(
									item.getInputStream(), tempFile);
							request.setAttribute("filepath",
									tempFile.getAbsolutePath());
						}
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
				chain.doFilter(request, response);
			} catch (OutOfMemoryError e) {
				throw new ServletException(
						"El servidor no tiene suficiente memoria para completar su solicitud.",
						e);
			}
		else
			chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
